const express = require('express');
const router = express.Router();
const Personnel = require('../models/Personnel');
const Changelog = require('../models/Changelog');

// 获取所有人员
router.get('/', async (req, res) => {
  try {
    const { organization, status, sortBy, order, page = 1, limit = 20, search } = req.query;
    
    // 构建查询条件
    const query = {};
    if (organization) query.organization = organization;
    if (status) query.status = status;
    if (search) {
      query.$or = [
        { name: { $regex: search, $options: 'i' } },
        { position: { $regex: search, $options: 'i' } }
      ];
    }
    
    // 构建排序条件
    const sortOptions = {};
    if (sortBy) {
      sortOptions[sortBy] = order === 'desc' ? -1 : 1;
    } else {
      sortOptions.lastUpdated = -1; // 默认按最后更新时间降序
    }
    
    // 分页
    const skip = (parseInt(page) - 1) * parseInt(limit);
    
    // 查询总数
    const total = await Personnel.countDocuments(query);
    
    // 查询数据
    const personnel = await Personnel.find(query)
      .sort(sortOptions)
      .skip(skip)
      .limit(parseInt(limit))
      .populate('sourceId', 'name organization');
    
    res.json({
      personnel,
      pagination: {
        total,
        page: parseInt(page),
        limit: parseInt(limit),
        pages: Math.ceil(total / parseInt(limit))
      }
    });
  } catch (error) {
    console.error('获取人员列表失败:', error);
    res.status(500).json({ message: '服务器错误', error: error.message });
  }
});

// 获取单个人员详情
router.get('/:id', async (req, res) => {
  try {
    const personnel = await Personnel.findById(req.params.id)
      .populate('sourceId', 'name organization listUrl');
    
    if (!personnel) {
      return res.status(404).json({ message: '人员不存在' });
    }
    
    // 获取该人员的变更历史
    const changelogs = await Changelog.find({ personnelId: req.params.id })
      .sort({ timestamp: -1 })
      .limit(10);
    
    res.json({ personnel, changelogs });
  } catch (error) {
    console.error('获取人员详情失败:', error);
    res.status(500).json({ message: '服务器错误', error: error.message });
  }
});

// 获取特定组织的人员列表
router.get('/organization/:org', async (req, res) => {
  try {
    const personnel = await Personnel.find({ 
      organization: req.params.org,
      status: { $ne: 'inactive' }
    })
      .sort({ name: 1 })
      .select('name position imageUrl detailUrl');
    
    res.json(personnel);
  } catch (error) {
    console.error('获取组织人员列表失败:', error);
    res.status(500).json({ message: '服务器错误', error: error.message });
  }
});

// 获取变更的人员列表
router.get('/changes/recent', async (req, res) => {
  try {
    const { days = 7, limit = 20 } = req.query;
    
    // 计算日期范围
    const startDate = new Date();
    startDate.setDate(startDate.getDate() - parseInt(days));
    
    // 获取最近的变更记录
    const changelogs = await Changelog.find({
      timestamp: { $gte: startDate }
    })
      .sort({ timestamp: -1 })
      .limit(parseInt(limit))
      .populate({
        path: 'personnelId',
        select: 'name position organization imageUrl detailUrl'
      })
      .populate({
        path: 'sourceId',
        select: 'name organization'
      });
    
    res.json(changelogs);
  } catch (error) {
    console.error('获取最近变更失败:', error);
    res.status(500).json({ message: '服务器错误', error: error.message });
  }
});

// 手动更新人员状态
router.patch('/:id/status', async (req, res) => {
  try {
    const { status } = req.body;
    
    if (!status || !['active', 'inactive', 'changed'].includes(status)) {
      return res.status(400).json({ message: '无效的状态值' });
    }
    
    const updatedPersonnel = await Personnel.findByIdAndUpdate(
      req.params.id,
      { status, lastUpdated: new Date() },
      { new: true }
    );
    
    if (!updatedPersonnel) {
      return res.status(404).json({ message: '人员不存在' });
    }
    
    res.json(updatedPersonnel);
  } catch (error) {
    console.error('更新人员状态失败:', error);
    res.status(500).json({ message: '服务器错误', error: error.message });
  }
});

// 获取所有活跃的组织列表
router.get('/organizations/list', async (req, res) => {
  try {
    const organizations = await Personnel.distinct('organization', { status: { $ne: 'inactive' } });
    res.json(organizations);
  } catch (error) {
    console.error('获取组织列表失败:', error);
    res.status(500).json({ message: '服务器错误', error: error.message });
  }
});

module.exports = router; 